package com.aqs.rwlook;


import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁
 * 独占锁（写锁），  一次只能被一个线程占用
 * 共享锁（读锁），   多个线程可以同时占用
 */
public class ReadWriteLockDemo {

    public static void main(String[] args) {

        MyCacheLock myCacheLock = new MyCacheLock();

        for (int i = 1; i <= 5; i++) {
            //写入操作
            int finalI = i;
            new Thread(() -> {
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                myCacheLock.put(String.valueOf(finalI), finalI + "");

            }, String.valueOf(i)).start();
        }

        for (int i = 1; i <= 5; i++) {
            //读取操作
            int finalI = i;
            new Thread(() -> {
                myCacheLock.get(String.valueOf(finalI));
            }, String.valueOf(i)).start();
        }


    }

}

/**
 * 自定义缓存
 */
class MyCache {

    private volatile Map<String, Object> map = new HashMap();

    public void put(String key, Object value) {
        System.out.println(Thread.currentThread().getName() + "准备写入" + key);
        map.put(key, value);
        System.out.println(Thread.currentThread().getName() + "写入ok");

    }

    public void get(String key) {
        System.out.println(Thread.currentThread().getName() + "准备读取" + key);

        System.out.println(Thread.currentThread().getName() + map.get(key));

    }


}

/**
 * 加锁的
 */
class MyCacheLock {

    private volatile Map<String, Object> map = new HashMap();
    //读写锁：更加细粒度的控制
    private ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();  //ReadWriteLock的实现类


    //写入的时候，只希望同时只有一个线程
    public void put(String key, Object value) {

        readWriteLock.writeLock().lock();  //写锁，加锁
        try {
            System.out.println(Thread.currentThread().getName() + "写入" + key);
            map.put(key, value);
            System.out.println(Thread.currentThread().getName() + "写入ok");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readWriteLock.writeLock().unlock(); //写锁，解锁
        }

    }

    //读的时候，所有人都可以读
    public void get(String key) {

        System.out.println(Thread.currentThread().getName() + "准备读取" + key);

        System.out.println(Thread.currentThread().getName() + "读取"+ map.get(key));

    }


}

